package de.wittekind.bjs.frontend;

import java.io.IOException;
import java.rmi.NotBoundException;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import de.wittekind.bundesjugendspiele.server.interfaces.Constants;

@ManagedBean(name = "configBean")
@SessionScoped
/**
 * @author Fynn Hauptmeier
 */
public class ConfigBean {

	private String host;
	private int port;
	private String name;

	public ConfigBean() {
		setName(Constants.RMI_NAME);
		setHost(Constants.SERVER_HOST);
		setPort(Constants.REGISTRY_PORT);

	}

	private RiegenBean getRiegenBean() {
		FacesContext context = FacesContext.getCurrentInstance();
		Application app = context.getApplication();
		ValueExpression expression = app.getExpressionFactory()
				.createValueExpression(context.getELContext(),
						String.format("#{%s}", "riegenBean"), Object.class);
		Object bean = expression.getValue(context.getELContext());
		if (bean instanceof RiegenBean) {
			return (RiegenBean) bean;
		}
		return null;
	}

	public void createConfig(ActionEvent ev) {
		RiegenBean riegenBean = getRiegenBean();
		FrontendConfig config = riegenBean.getConfig();
		config.setHost(host);
		config.setPort(port);
		config.setName(name);
		try {
			riegenBean.init();
		} catch (IOException | NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
